<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

class ApiController extends BaseController
{
    //实例化的模型仓库
    protected $repository;

    //请求的参数
    protected $request;

    //初始化
    public function __construct(Request $request)
    {
        $this->request = $request;

        $this->repository = $this->initControllerModelName();

        if(!$this->repository) {
            return abort(404,'request not found');
        }
    }

    //从请求中获取api的资源名称并实例化模型为repository
    protected function initControllerModelName()
    {
        if(!$this->repository && $routeName = $this->request->input('_model')) {
            if($repositoryName = config('repositoryRouteMap.admin.'.$routeName)){
                $repositoryName = 'App\Repositories\Admin\\'.$repositoryName.'Repository';

                $repository = new $repositoryName;
                $repository->request = $this->request;
                $repository->loginUser = $this->loginUser();
                return $repository;
            }
        }

        return false;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        return $this->repository->index($request);
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        return $this->repository->store($request);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return $this->repository->show($id);
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        return $this->repository->update($request, $id);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        return $this->repository->destroy($id);
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $ids
     * @return \Illuminate\Http\Response
     */
    public function destroyBatch(Request $request)
    {
        return $this->repository->destroyBatch($request);
    }

    public function export()
    {
        return $this->repository->export();
    }
}
